#include <QDebug>

#include <mysql_driver.h>
#include <cppconn/statement.h>

#include "mysqldbmanager.h"

namespace Jcr
{
class MySqlDbManagerPrivate
{
public:
    MySqlDbManagerPrivate();

    sql::Driver* driver = nullptr;
    sql::Connection* conn = nullptr;
};

MySqlDbManagerPrivate::MySqlDbManagerPrivate()
{
    driver = static_cast<sql::Driver*>(get_driver_instance());

    try {
        conn = driver->connect("localhost", "root", "13246687");
    } catch (std::exception& exp) {
        qDebug() << exp.what();
    }
}

MySqlDbManager::MySqlDbManager(QObject *parent) : QObject(parent)
{
    d_ptr = new MySqlDbManagerPrivate;
}

MySqlDbManager::~MySqlDbManager()
{
    delete d_ptr;
}

MySqlDbManager* MySqlDbManager::instance()
{
    static MySqlDbManager _inst;
    return &_inst;
}

bool MySqlDbManager::connect(const QString &server, const QString &user, const QString &password)
{
    if (d_ptr->conn) {
        d_ptr->conn->close();
        delete d_ptr->conn;
        d_ptr->conn = nullptr;
    }

    d_ptr->conn = d_ptr->driver->connect(sql::SQLString(server.toStdString()),
                                         sql::SQLString(user.toStdString()),
                                         sql::SQLString(password.toStdString()));
    return d_ptr->conn != nullptr;
}

} // namespace jcr
